package com.tim.app.db.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import com.application.library.log.DLOG;
import com.application.library.runtime.event.EventManager;
import com.google.gson.Gson;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.tim.app.constant.EventTag;
import com.tim.app.db.model.NoticeModel;
import com.tim.app.server.entry.Notice;

import java.util.ArrayList;


/**
 * 通知的数据库
 *
 * @author fanxiaofeng
 * @date 2016年3月29日
 */
public class NoticeDao extends GlobalHelperDao {

    public NoticeDao(Context context) {
        super(context);
    }


    @Override
    public void clearData() {
        super.clearData();
    }

    /**
     * 添加消息
     *
     * @param notice
     * @return
     */
    public synchronized boolean addMessage(Notice notice) {

        boolean resultValue = true;
        try {
            if (notice != null) {

                openWritableDB();
                ContentValues cv = createContentValues(notice);
                long row = insert(NoticeModel.TABLE_NAME, null, cv);
                if (row == -1) {
                    resultValue = false;
                }
                sendUnReadMessageCountChanged();
                //TODO
            }

        } catch (DaoException e) {
            DLOG.d(TAG, e.toString());
            resultValue = false;
        } finally {
            closeDB();
        }
        return resultValue;

    }

    /**
     * 更新已读状态
     *
     * @return
     */
    public void updataReadState(String type) {
        try {
            openWritableDB();

            StringBuilder sql = new StringBuilder();

            sql.append("update ")
                    .append(NoticeModel.TABLE_NAME)
                    .append(" set ").append(NoticeModel.COLUMN_NAME[NoticeModel.IS_READ])
                    .append(" = 1")
                    .append(" where ")
                    .append(NoticeModel.COLUMN_NAME[NoticeModel.IS_READ])
                    .append(" = 0 ").append(" and ").append(NoticeModel.COLUMN_NAME[NoticeModel.TYPE]).append(" =  \'" + type + "\'");
            execSql(sql.toString());
            sendNoticeMessageCountChanged();
            sendUnReadMessageCountChanged();
        } catch (DaoException e) {
            DLOG.e(TAG, e.toString());
        } finally {
            closeDB();
        }
    }

    /**
     * 返回通知
     *
     * @return
     */
    public ArrayList<Notice> getNotices(int pageSize, String type) {

        Cursor cursor = null;
        ArrayList<Notice> notices = new ArrayList<Notice>();
        try {
            openReadableDB();

            StringBuilder sql = new StringBuilder();

            sql.append("select * from ")
                    .append(NoticeModel.TABLE_NAME).append(" where ").append(NoticeModel.COLUMN_NAME[NoticeModel.TYPE])
                    .append(" = ? ").append(" order by ")
                    .append(NoticeModel.COLUMN_NAME[NoticeModel.TIME])
                    .append(" desc limit ? ");
            cursor = query(sql.toString(), new String[]{type, String.valueOf(pageSize)});
            if (checkCursorAvaible(cursor)) {
                while (cursor.moveToNext()) {
                    Notice notice = createMessageModel(cursor);
                    notices.add(notice);
                }
            }
        } catch (DaoException e) {
            DLOG.e(TAG, e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            closeDB();
        }
        return notices;
    }

    /**
     * 返回通知
     *
     * @return
     */
    public ArrayList<Notice> getNoticeByTime(long time, int pageSize, String type) {

        Cursor cursor = null;
        ArrayList<Notice> notices = new ArrayList<Notice>();
        try {
            openReadableDB();

            StringBuilder sql = new StringBuilder();

            sql.append("select * from ")
                    .append(NoticeModel.TABLE_NAME).append("  where  ")
                    .append(NoticeModel.COLUMN_NAME[NoticeModel.TIME])
                    .append(" < ? ").append(" and ")
                    .append(NoticeModel.COLUMN_NAME[NoticeModel.TYPE])
                    .append(" = ? ")
                    .append(" order by ")
                    .append(NoticeModel.COLUMN_NAME[NoticeModel.TIME]).append(" desc ")
                    .append(" limit ? ");
            cursor = query(sql.toString(), new String[]{String.valueOf(time), type, String.valueOf(pageSize)});
            if (checkCursorAvaible(cursor)) {
                while (cursor.moveToNext()) {
                    Notice notice = createMessageModel(cursor);
                    notices.add(notice);
                }
            }
        } catch (DaoException e) {
            DLOG.e(TAG, e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            closeDB();
        }
        return notices;
    }


    /**
     * 删除某条消息
     *
     * @return
     */
    public boolean deleteMessage(String id) {

        boolean result = false;
        try {
            openWritableDB();
            result = delete(
                    NoticeModel.TABLE_NAME,
                    NoticeModel.COLUMN_NAME[NoticeModel.ID]
                            + " = ?", new String[]{id});
            if (result) {
                sendUnReadMessageCountChanged();
            }
        } catch (DaoException e) {
            DLOG.d(TAG, e.toString());
        } finally {
            closeDB();
        }
        return result;

    }

    /**
     * 清除所有消息
     *
     * @return
     */
    public boolean clearMessageData() {
        boolean resultValue = false;
        try {
            openWritableDB();
            resultValue = delete(NoticeModel.TABLE_NAME, null, null);
            if (resultValue) {
                sendUnReadMessageCountChanged();
            }
        } catch (DaoException e) {
            DLOG.e(TAG, e.toString());
        } finally {
            closeDB();
        }
        return resultValue;
    }

    /**
     * 获取未读消息的数量
     *
     * @return
     */
    public int getUnReadMessageCountByType(String type) {
        int count = 0;
        Cursor countCursor = null;

        try {
            openReadableDB();
            StringBuilder countSql = new StringBuilder();

            countSql.append("select count(*) from ").append(
                    NoticeModel.TABLE_NAME).append(" where ")
                    .append(NoticeModel.COLUMN_NAME[NoticeModel.IS_READ])
                    .append(" = ?").append(" and ").append(NoticeModel.COLUMN_NAME[NoticeModel.TYPE]).append(" = ?");

            countCursor = query(countSql.toString(), new String[]{"0", type});
            if (checkCursorAvaible(countCursor)) {
                countCursor.moveToNext();
                count = countCursor.getInt(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (countCursor != null) {
                countCursor.close();
            }
            closeDB();
        }
        return count;
    }


    /**
     * 获取未读消息的数量
     *
     * @return
     */
    public int getUnReadMessageCount() {
        int count = 0;
        Cursor countCursor = null;

        try {
            openReadableDB();
            StringBuilder countSql = new StringBuilder();

            countSql.append("select count(*) from ").append(
                    NoticeModel.TABLE_NAME).append(" where ")
                    .append(NoticeModel.COLUMN_NAME[NoticeModel.IS_READ])
                    .append(" = ?");

            countCursor = query(countSql.toString(), new String[]{"0"});
            if (checkCursorAvaible(countCursor)) {
                countCursor.moveToNext();
                count = countCursor.getInt(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (countCursor != null) {
                countCursor.close();
            }
            closeDB();
        }
        return count;
    }

    public int getNoticeCount() {
        int count = 0;
        Cursor countCursor = null;

        try {
            openReadableDB();
            StringBuilder countSql = new StringBuilder();

            countSql.append("select count(*) from ").append(
                    NoticeModel.TABLE_NAME);

            countCursor = query(countSql.toString());
            if (checkCursorAvaible(countCursor)) {
                countCursor.moveToNext();
                count = countCursor.getInt(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (countCursor != null) {
                countCursor.close();
            }
            closeDB();
        }

        return count;

    }

    static Notice createMessageModel(Cursor cursor) {

        String noticeId = cursor
                .getString(NoticeModel.ID);
        String content = cursor.getString(NoticeModel.CONTENT);
        Notice notice = new Gson().fromJson(content, Notice.class);
        notice.setNoticeId(noticeId);
        notice.setNoticitifyContent(content);
        int i = cursor.getInt(NoticeModel.IS_READ);
        notice.setRead(i == 1 ? true
                : false);
        notice.setTime(cursor.getLong(NoticeModel.TIME));
        notice.setInsertType(cursor.getString(NoticeModel.TYPE));
        return notice;
    }

    private ContentValues createContentValues(Notice notice) {

        ContentValues contentValues = new ContentValues();

        if (!TextUtils.isEmpty(notice.getNoticitifyContent())) {
            contentValues
                    .put(NoticeModel.COLUMN_NAME[NoticeModel.CONTENT],
                            notice.getNoticitifyContent());
        }
        contentValues.put(
                NoticeModel.COLUMN_NAME[NoticeModel.IS_READ],
                notice.isRead() == true ? 1 : 0);
        contentValues.put(
                NoticeModel.COLUMN_NAME[NoticeModel.TIME],
                notice.getTime());
        if (notice.getOperation().equals("action")) {
            contentValues.put(
                    NoticeModel.COLUMN_NAME[NoticeModel.TYPE],
                    notice.getActionType());
        } else {
            contentValues.put(
                    NoticeModel.COLUMN_NAME[NoticeModel.TYPE],
                    notice.getOperation());
        }
        return contentValues;

    }

    @Override
    String getTableName() {

        return NoticeModel.TABLE_NAME;

    }


    /**
     * 发送未读消息变化通知
     */
    public void sendUnReadMessageCountChanged() {
        final int unReadMessageTotalCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();
        EventManager.ins().sendEvent(EventTag.ON_READ_MESSAGE_COUNT, 0, 0, unReadMessageTotalCount);
    }

    /**
     * 发送通知消息变化通知
     */
    public void sendNoticeMessageCountChanged() {
        final int unReadMessageTotalCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();
        EventManager.ins().sendEvent(EventTag.ON_NOTICE_MESSAGE_STATED_CHANGED, 0, 0, unReadMessageTotalCount);
    }

}
